VanyAjax.baseUrl = baseUrl = "";
VanyAjax.token = token = sessionStorage.token;
$("#userName #userNameAfterWelcome").html(sessionStorage.username);
//  =======================
//  ====== 右上角编辑 ======
//  =======================
var myProfile = new Vue({
    el: '#userinfo',
    methods: {
        //个人资料加载
        personal: function () {
            editMyProfile.getData();
        },
        //修改密码
        changePassword: function () {
            resetPwd.show();
        },
        //退出
        logout: function () {
            var form = $('<form target="_self" method="post" action="/logout" target="self"><input type="text" name="token" value="' + sessionStorage.token + '" /></form>')
            $(document.body).append(form);
            form.submit();
            sessionStorage.clear();
        }
    }
});

//修改密码
var resetPwd = new Vue({
    el: "#resetPwd",
    data: function () {
        //再次输入新密码
        var self = this;
        var validatePass = function (rule, value, callback) {
            if (value === '') {
                callback(new Error('密码不能为空'));
            } else {
                if (self.ruleForm.surePassword !== '') {
                    self.$refs.ruleForm.validateField('surePassword');
                }
                callback();
            }
        };
        var validatePass2 = function (rule, value, callback) {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== self.ruleForm.newPassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            resetPwdVisible: false,
            labelPosition: 'right',
            ruleForm: {
                oldPassword: '',
                newPassword: '',
                surePassword: ''
            },
            rules: {
                oldPassword: {
                    required: true,
                    message: '请输入原始密码',
                    trigger: 'blur'
                },
                newPassword: {
                    required: true,
                    validator: validatePass,
                    trigger: 'blur'
                },
                surePassword: {
                    required: true,
                    validator: validatePass2,
                    trigger: 'blur'
                }
            }
        };
    },
    methods: {
        show: function () {
            this.resetForm();
            this.resetPwdVisible = true;
        },
        hide: function () {
            this.resetPwdVisible = false;
        },
        resetForm: function () {
            try {
                resetPwd.$refs["ruleForm"].resetFields();
            } catch (e) {

            }
            this.ruleForm.oldPassword = '';
            this.ruleForm.newPassword = '';
            this.ruleForm.surePassword = '';
        },
        submitForm: function (formName) {
            var self = this;
            self.$refs[formName].validate(function (valid) {
                if (valid) {
                    VanyAjax("/index/updateUserPassword", self.ruleForm).done(function () {
                        this.resetForm();
                        this.hide();
                    }, true, self);
                    /*resetPwd.resetPwdVisible = false;
                    $.ajax({
                        url: "/index/updateUserPassword",
                        method: "POST",
                        async: false,
                        data: {
                            "token": sessionStorage.token,
                            "oldPassword": resetPwd.ruleForm.oldPassword,
                            "newPassword": resetPwd.ruleForm.newPassword
                        },
                        success: function(data) {
                            if(data.rspCode === '000000') {
                                self.$message.success(data.rspMsg);
                            } else {
                                self.$message.error(data.rspMsg);
                            }
                            //							localStorage.removeItem(localStorage.userPasswod); //清空缓存中的密码
                            resetPwd.ruleForm.oldPassword = '';
                            resetPwd.ruleForm.newPassword = '';
                            resetPwd.ruleForm.surePassword = '';
                        }
                    });*/
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
});

//修改人员
var editMyProfile = new Vue({
    el: "#usernewPerson",
    data: function () {
        return {
            newPersonVisible: false,
            labelPosition: "left",
            form: {
                userCode: "",
                userName: "",
                // 用于上传图片
                photo: "",
                gender: "",
                tel: "",
                mobile: "",
                wechat: "",
                identificationTypeCode: "01",
                identificationNo: "",
                email: "",
                orgInfo: ""
            },
            // 用于展示，图片的保存路径
            photoUrl: "/templates/img/default.jpg",
            orgInfo: [],
            identificationTypeCode: [],
            rules: {
                userName: [{
                    required: true,
                    message: "名称不能为空",
                    trigger: 'blur'
                }],
                tel: [{
                    trigger: 'blur',
                    validator: function (rule, value, callback) {
                        if (value === "" || value === null) {
                            callback();
                        } else {
                            if (!/^[0-9]*$/.test(value)) {
                                callback(new Error("公司电话只能为数字"));
                            } else {
                                callback();
                            }
                        }
                    }
                }],
                mobile: [{
                    required: false,
                    trigger: 'blur',
                    validator: function (rule, value, callback) {
                        if (value === "" || value === null) {
                            callback();
                        } else {
                            if (!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(value))) {
                                callback(new Error("请输入正确的手机号"));
                            } else {
                                callback();
                            }
                        }
                    }
                }],
                email: [{
                    type: 'email',
                    message: '请输入正确的邮箱地址',
                    trigger: 'blur'
                }]
            }
        }
    },
    created: function () {
        VanyAjax("/base/dictionary/identification", {}, "GET").done(function (data) {
            for (var i = 0; i < data.length; i++) {
                this.identificationTypeCode.push({
                    value: data[i].identificationTypeCode,
                    label: data[i].identificationTypeName
                });
            }
        }, false, this);
    },
    methods: {
        show: function () {
            this.newPersonVisible = true;
        },
        hide: function () {
            this.newPersonVisible = false;
        },
        getData: function () {
            VanyAjax("/index/queryUserInfo", {}, "GET").done(function (data) {
                var self = this;
                var userInfo = data.userInfo;
                for (var key in userInfo) {
                    this.form[key] = userInfo[key];
                    if (key == 'photoUrl') {
                        if (userInfo[key] == '' || userInfo[key] == null) {
                            this[key] = "/templates/img/default.jpg";
                        } else {
                            this[key] = userInfo[key] + "?" + +new Date();
                        }
                    }
                }
                // 手动转换以下字段格式
                // *List由数组变为逗号隔开的字符串,默认部门
                var orgInfo = data.orgInfo;
                if (orgInfo) {
                    this.form.orgInfo = orgInfo.map(function (item) {
                        self.orgInfo.push({
                            id: item.orgCode,
                            name: item.orgName
                        });
                        return item.orgCode;
                    }).join(",");
                }
                this.show();
            }, false, this);
        },
        beforeAvatarUpload: function (file) {
            var isJPG = file.type === 'image/jpeg';
            var isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        save: function (e) {
            var self = this;
            this.$refs["newPersonForm"].validate(function (valid) {
                if (!valid) {
                    e.stopPropagation();
                    return false;
                }
                VanyAjax("index/updateUserInfo", self.form).done(function (data) {
                    self.hide();
                }, true, self);
            });
        },
        resetForm: function () {
            this.$refs["newPersonForm"].resetFields();
            this.form.userAccount = "";
            this.form.userName = "";
            this.form.gender = "1";
            this.form.mobile = "";
            this.form.tel = "";
            this.form.email = "";
            this.form.identificationNo = "";
            this.form.identificationTypeCode = '01';
            this.photoUrl = "/templates/img/default.jpg";
            this.form.wechat = "";
            this.form.orgInfo = "";
            this.orgInfo = [];
        },
        /*重置表单值*/
        close: function () {
            this.resetForm();
        },
        handleChange: function (file, fileList) {
            userAvaterCropper.dialogVisible = true;
            userAvaterCropper.imgSrc = file.url;
            setTimeout(function () {
                userAvaterCropper.initCropper("avater_be_cropper");
            }, 500);
        },
    }
});

/*头像裁剪器*/
var userAvaterCropper = new Vue({
    el: "#userindexUserCropper",
    data: function () {
        return {
            dialogVisible: false,
            imgSrc: "",
            cropper: ""
        }
    },
    methods: {
        updateAvater: function (isUpated) {
            if (isUpated) {
                var canvas = this.cropper.getCroppedCanvas({
                    width: 320,
                    height: 320
                });
                editMyProfile.form.photo = canvas.toDataURL('image/jpeg');
                editMyProfile.photoUrl = canvas.toDataURL('image/jpeg');
            }
            this.imgSrc = "";
            this.cropper.destroy();
            this.dialogVisible = false;
        },
        initCropper: function (imgEl) {
            var image_ = document.getElementById(imgEl);
            this.cropper = new Cropper(image_, {
                viewMode: 1,
                aspectRatio: 1 / 1
            });
        }
    }
});